package health_system.health_system.websocket.Model;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 聊天消息处理器
 * 处理WebSocket消息的Spring处理器实现
 */
@Component
public class ChatMessageHandler extends TextWebSocketHandler {
    private static final Logger logger = Logger.getLogger(ChatMessageHandler.class.getName());
    private static final ObjectMapper mapper = new ObjectMapper();
    
    // 会话映射表，用于保存所有WebSocket会话
    private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    
    // 用户会话映射表，用于通过用户名查找会话
    private static final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();
    
    // 好友关系映射表
    private static final Map<String, Set<String>> friendships = new ConcurrentHashMap<>();
    
    // 分块传输映射表，用于处理大文件的分块传输
    private static final Map<String, Map<Integer, String>> chunkTransfers = new ConcurrentHashMap<>();
    
    /**
     * 处理WebSocket连接建立事件
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String sessionId = session.getId();
        sessions.put(sessionId, session);
        
        // 从会话属性中获取用户名
        String username = extractUsername(session);
        if (username != null) {
            userSessions.put(username, session);
            logger.info("用户 " + username + " 已连接，会话ID: " + sessionId);
            
            // 初始化用户的好友列表
            friendships.putIfAbsent(username, ConcurrentHashMap.newKeySet());
            
            // 通知该用户的好友其已上线
            notifyFriendsOfStatusChange(username, true);
            
            // 发送离线消息（此处仅为示例）
            sendOfflineMessages(username);
        } else {
            logger.warning("无法识别的用户连接: " + sessionId);
        }
    }

    /**
     * 处理WebSocket连接关闭事件
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String sessionId = session.getId();
        String username = extractUsername(session);
        
        if (username != null) {
            userSessions.remove(username);
            logger.info("用户 " + username + " 已断开连接，会话ID: " + sessionId);
            
            // 通知该用户的好友其已离线
            notifyFriendsOfStatusChange(username, false);
        }
        
        sessions.remove(sessionId);
    }

    /**
     * 处理WebSocket消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) {
        String payload = textMessage.getPayload();
        if (payload == null || payload.isEmpty()) {
            logger.warning("收到空消息，会话ID: " + session.getId());
            return;
        }
        
        try {
            // 解析消息
            ChatMessage message = mapper.readValue(payload, ChatMessage.class);
            String type = message.getType();
            String fromUser = message.getFromUser();
            String toUser = message.getToUser();
            
            // 验证发送者身份
            String sessionUsername = extractUsername(session);
            if (!fromUser.equals(sessionUsername)) {
                sendErrorMessage(session, "消息发送者身份验证失败");
                return;
            }
            
            // 根据消息类型进行不同处理
            MessageType messageType = MessageType.fromString(type);
            if (messageType == null) {
                logger.warning("未知消息类型: " + type);
                return;
            }
            
            switch (messageType) {
                case CHAT_MESSAGE:
                    handleChatMessage(message);
                    break;
                case FRIEND_REQUEST:
                    handleFriendRequest(message);
                    break;
                case FRIEND_RESPONSE:
                    handleFriendResponse(message);
                    break;
                case SOCIAL_POST:
                    handleSocialPost(message);
                    break;
                case SOCIAL_INTERACTION:
                    handleSocialInteraction(message);
                    break;
                case TYPING_INDICATOR:
                    handleTypingIndicator(message);
                    break;
                case READ_RECEIPT:
                    handleReadReceipt(message);
                    break;
                case MEDIA_TRANSFER:
                    handleMediaTransfer(message);
                    break;
                default:
                    logger.warning("未处理的消息类型: " + type);
            }
            
        } catch (IOException e) {
            logger.log(Level.SEVERE, "处理消息时出错", e);
            sendErrorMessage(session, "消息处理失败: " + e.getMessage());
        }
    }

    /**
     * 处理WebSocket错误
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        String sessionId = session.getId();
        String username = extractUsername(session);
        
        logger.log(Level.SEVERE, "WebSocket传输错误，会话ID: " + sessionId + 
                (username != null ? "，用户名: " + username : ""), exception);
    }

    /**
     * 处理聊天消息
     */
    private void handleChatMessage(ChatMessage message) throws IOException {
        String fromUser = message.getFromUser();
        String toUser = message.getToUser();
        String contentType = message.getContentType();
        
        // 验证消息大小是否符合限制
        if (!validateMessageSize(message)) {
            sendErrorToUser(fromUser, "消息超出大小限制");
            return;
        }
        
        // 验证发送者和接收者是否为好友关系
        if (!areFriends(fromUser, toUser)) {
            sendErrorToUser(fromUser, "无法发送消息，对方不是您的好友");
            return;
        }
        
        // 生成消息ID和时间戳
        if (message.getMessageId() == null) {
            message.setMessageId(generateMessageId());
        }
        message.setTimestamp(System.currentTimeMillis());
        
        // 标记消息为未读
        message.setRead(false);
        
        WebSocketSession toUserSession = userSessions.get(toUser);
        
        if (toUserSession != null && toUserSession.isOpen()) {
            // 接收者在线，直接发送消息
            sendMessage(toUserSession, message);
            
            // 发送发送成功的确认给发送者
            sendDeliveryConfirmation(fromUser, message.getMessageId(), DeliveryStatus.SENT);
        } else {
            // 接收者不在线，存储离线消息（此处需实现持久化存储）
            // ...
            
            // 发送离线通知给发送者
            sendDeliveryConfirmation(fromUser, message.getMessageId(), DeliveryStatus.PENDING);
        }
    }
    
    /**
     * 处理好友请求
     */
    private void handleFriendRequest(ChatMessage message) throws IOException {
        String fromUser = message.getFromUser();
        String toUser = message.getToUser();
        
        WebSocketSession toUserSession = userSessions.get(toUser);
        
        if (toUserSession != null && toUserSession.isOpen()) {
            // 用户在线，发送好友请求
            sendMessage(toUserSession, message);
        } else {
            // 用户不在线，存储离线请求（此处需实现持久化存储）
            // ...
            
            sendSystemMessageToUser(fromUser, "用户" + toUser + "当前不在线，请求将在其上线后发送");
        }
    }
    
    /**
     * 处理好友请求响应
     */
    private void handleFriendResponse(ChatMessage message) throws IOException {
        String fromUser = message.getFromUser();
        String toUser = message.getToUser();
        Boolean accepted = Boolean.parseBoolean(message.getContent());
        
        if (accepted) {
            // 接受好友请求，更新好友关系
            addFriend(fromUser, toUser);
            
            // 通知双方好友关系已建立
            sendSystemMessageToUser(fromUser, "您已添加 " + toUser + " 为好友");
            sendSystemMessageToUser(toUser, fromUser + " 已接受您的好友请求");
        } else {
            // 拒绝好友请求，通知发送方
            sendSystemMessageToUser(toUser, fromUser + " 拒绝了您的好友请求");
        }
    }
    
    /**
     * 处理社交动态发布
     */
    private void handleSocialPost(ChatMessage message) throws IOException {
        String fromUser = message.getFromUser();
        
        // 生成社交动态ID和时间戳
        if (message.getMessageId() == null) {
            message.setMessageId(generateMessageId());
        }
        message.setTimestamp(System.currentTimeMillis());
        
        // 处理媒体内容（实际实现中应存储到服务器）
        if (!MessageContentType.TEXT.getValue().equals(message.getContentType())) {
            // 处理媒体文件存储和URL生成
            String mediaUrl = processAndStoreMedia(message);
            message.setContent(mediaUrl);
        }
        
        // 获取发布者的所有好友
        Set<String> friends = friendships.getOrDefault(fromUser, Collections.emptySet());
        
        // 通知所有在线好友有新动态
        for (String friend : friends) {
            WebSocketSession friendSession = userSessions.get(friend);
            if (friendSession != null && friendSession.isOpen()) {
                sendMessage(friendSession, message);
            }
            // 对不在线的好友，实际实现中应存储到数据库，待上线后通知
        }
        
        // 发送确认给发布者
        sendSystemMessageToUser(fromUser, "朋友圈动态已发布");
    }
    
    /**
     * 处理社交互动（点赞、评论等）
     */
    private void handleSocialInteraction(ChatMessage message) throws IOException {
        String fromUser = message.getFromUser();
        String toUser = message.getToUser();
        String postId = message.getRelatedMessageId();
        SocialInteractionType interactionType = SocialInteractionType.fromString(message.getContent());
        
        if (interactionType == null || postId == null) {
            sendErrorToUser(fromUser, "无效的社交互动请求");
            return;
        }
        
        // 生成互动ID和时间戳
        if (message.getMessageId() == null) {
            message.setMessageId(generateMessageId());
        }
        message.setTimestamp(System.currentTimeMillis());
        
        // 通知帖子所有者有新互动
        WebSocketSession toUserSession = userSessions.get(toUser);
        if (toUserSession != null && toUserSession.isOpen()) {
            sendMessage(toUserSession, message);
        }
        // 对不在线的用户，实际实现中应存储到数据库，待上线后通知
        
        // 发送确认给互动者
        switch (interactionType) {
            case LIKE:
                sendSystemMessageToUser(fromUser, "您已点赞该动态");
                break;
            case COMMENT:
                sendSystemMessageToUser(fromUser, "您的评论已发布");
                break;
            case SHARE:
                sendSystemMessageToUser(fromUser, "您已成功分享该动态");
                break;
        }
    }
    
    /**
     * 处理正在输入指示器
     */
    private void handleTypingIndicator(ChatMessage message) throws IOException {
        String toUser = message.getToUser();
        
        WebSocketSession toUserSession = userSessions.get(toUser);
        if (toUserSession != null && toUserSession.isOpen()) {
            // 直接转发指示器消息给接收者
            sendMessage(toUserSession, message);
        }
    }
    
    /**
     * 处理已读回执
     */
    private void handleReadReceipt(ChatMessage message) throws IOException {
        String toUser = message.getToUser();
        String messageId = message.getRelatedMessageId();
        
        if (messageId == null) {
            return;
        }
        
        WebSocketSession toUserSession = userSessions.get(toUser);
        if (toUserSession != null && toUserSession.isOpen()) {
            // 发送已读回执给原消息发送者
            message.setRead(true);
            sendMessage(toUserSession, message);
        }
        // 对不在线的用户，实际实现中应存储到数据库
    }
    
    /**
     * 处理媒体传输消息
     */
    private void handleMediaTransfer(ChatMessage message) throws IOException {
        String fromUser = message.getFromUser();
        String toUser = message.getToUser();
        Integer chunkIndex = message.getChunkIndex();
        Integer totalChunks = message.getTotalChunks();
        String messageId = message.getMessageId();
        
        // 验证分块信息
        if (chunkIndex == null || totalChunks == null || messageId == null) {
            sendErrorToUser(fromUser, "无效的媒体传输请求");
            return;
        }
        
        // 如果是多媒体聊天内容（图片、视频、语音等），执行端到端转发，不存储
        if (!MessageContentType.TEXT.getValue().equals(message.getContentType()) && 
            !isSocialMedia(message)) {
            
            WebSocketSession toUserSession = userSessions.get(toUser);
            if (toUserSession != null && toUserSession.isOpen()) {
                // 直接转发给接收者
                sendMessage(toUserSession, message);
                
                // 如果是最后一个分块，发送传输完成确认
                if (chunkIndex.equals(totalChunks - 1)) {
                    sendDeliveryConfirmation(fromUser, messageId, DeliveryStatus.DELIVERED);
                }
            } else {
                // 接收者不在线，返回错误
                sendErrorToUser(fromUser, "用户" + toUser + "不在线，无法传输媒体内容");
                
                // 清理可能已缓存的分块
                synchronized (chunkTransfers) {
                    chunkTransfers.remove(messageId);
                }
            }
        }
    }
    
    /**
     * 从会话中提取用户名
     */
    private String extractUsername(WebSocketSession session) {
        // 从会话属性或URI参数中提取用户名
        Map<String, Object> attributes = session.getAttributes();
        if (attributes.containsKey("username")) {
            return (String) attributes.get("username");
        }
        
        // 从URI查询参数中提取
        String query = session.getUri() != null ? session.getUri().getQuery() : null;
        if (query != null && query.contains("username=")) {
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                if (pair.startsWith("username=")) {
                    return pair.substring("username=".length());
                }
            }
        }
        
        return null;
    }
    
    /**
     * 发送消息到指定会话
     */
    private void sendMessage(WebSocketSession session, ChatMessage message) {
        try {
            String jsonMessage = mapper.writeValueAsString(message);
            sendMessage(session, jsonMessage);
        } catch (JsonProcessingException e) {
            logger.log(Level.SEVERE, "序列化消息失败", e);
        }
    }
    
    /**
     * 发送文本消息到指定会话
     */
    private void sendMessage(WebSocketSession session, String jsonMessage) {
        if (session == null || !session.isOpen()) {
            logger.warning("尝试向无效会话发送消息");
            return;
        }
        
        try {
            TextMessage textMessage = new TextMessage(jsonMessage);
            synchronized (session) {
                session.sendMessage(textMessage);
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "发送消息时出错", e);
        }
    }
    
    /**
     * 发送系统消息给指定用户
     */
    private void sendSystemMessageToUser(String username, String content) {
        WebSocketSession userSession = userSessions.get(username);
        if (userSession != null && userSession.isOpen()) {
            ChatMessage systemMessage = new ChatMessage();
            systemMessage.setType(MessageType.SYSTEM_NOTIFICATION.getValue());
            systemMessage.setFromUser("系统");
            systemMessage.setToUser(username);
            systemMessage.setContentType(MessageContentType.TEXT.getValue());
            systemMessage.setContent(content);
            systemMessage.setTimestamp(System.currentTimeMillis());
            systemMessage.setMessageId(generateMessageId());
            
            sendMessage(userSession, systemMessage);
        }
    }
    
    /**
     * 发送错误消息给指定用户
     */
    private void sendErrorToUser(String username, String errorMessage) {
        WebSocketSession userSession = userSessions.get(username);
        if (userSession != null && userSession.isOpen()) {
            sendErrorMessage(userSession, errorMessage);
        }
    }
    
    /**
     * 发送错误消息给指定会话
     */
    private void sendErrorMessage(WebSocketSession session, String errorMessage) {
        ChatMessage errorMsg = new ChatMessage();
        errorMsg.setType(MessageType.ERROR.getValue());
        errorMsg.setFromUser("系统");
        errorMsg.setToUser(extractUsername(session));
        errorMsg.setContentType(MessageContentType.TEXT.getValue());
        errorMsg.setContent(errorMessage);
        errorMsg.setTimestamp(System.currentTimeMillis());
        
        sendMessage(session, errorMsg);
    }
    
    /**
     * 发送传递确认消息
     */
    private void sendDeliveryConfirmation(String username, String messageId, DeliveryStatus status) {
        WebSocketSession userSession = userSessions.get(username);
        if (userSession != null && userSession.isOpen()) {
            ChatMessage confirmationMsg = new ChatMessage();
            confirmationMsg.setType(MessageType.DELIVERY_STATUS.getValue());
            confirmationMsg.setFromUser("系统");
            confirmationMsg.setToUser(username);
            confirmationMsg.setContentType(MessageContentType.TEXT.getValue());
            confirmationMsg.setRelatedMessageId(messageId);
            confirmationMsg.setContent(status.getValue());
            confirmationMsg.setTimestamp(System.currentTimeMillis());
            
            sendMessage(userSession, confirmationMsg);
        }
    }
    
    /**
     * 通知好友状态变化（上线/离线）
     */
    private void notifyFriendsOfStatusChange(String username, boolean isOnline) {
        Set<String> friends = friendships.getOrDefault(username, Collections.emptySet());
        
        for (String friend : friends) {
            WebSocketSession friendSession = userSessions.get(friend);
            if (friendSession != null && friendSession.isOpen()) {
                ChatMessage statusMsg = new ChatMessage();
                statusMsg.setType(MessageType.FRIEND_STATUS.getValue());
                statusMsg.setFromUser(username);
                statusMsg.setToUser(friend);
                statusMsg.setContentType(MessageContentType.TEXT.getValue());
                statusMsg.setContent(isOnline ? "online" : "offline");
                statusMsg.setTimestamp(System.currentTimeMillis());
                
                sendMessage(friendSession, statusMsg);
            }
        }
    }
    
    /**
     * 发送离线消息
     */
    private void sendOfflineMessages(String username) {
        // 实际实现中应从数据库获取离线消息并发送
        // 这里仅作为示例
    }
    
    /**
     * 检验消息大小是否超过限制
     */
    private boolean validateMessageSize(ChatMessage message) {
        // 实际应用中，应该根据消息内容类型和系统配置进行限制
        return true;
    }
    
    /**
     * 检查两个用户是否为好友关系
     */
    private boolean areFriends(String user1, String user2) {
        Set<String> user1Friends = friendships.getOrDefault(user1, Collections.emptySet());
        return user1Friends.contains(user2);
    }
    
    /**
     * 添加好友关系（双向）
     */
    private void addFriend(String user1, String user2) {
        friendships.computeIfAbsent(user1, k -> ConcurrentHashMap.newKeySet()).add(user2);
        friendships.computeIfAbsent(user2, k -> ConcurrentHashMap.newKeySet()).add(user1);
    }
    
    /**
     * 判断消息是否为社交媒体内容（允许存储）
     */
    private boolean isSocialMedia(ChatMessage message) {
        String type = message.getType();
        return MessageType.SOCIAL_POST.getValue().equals(type) ||
               MessageType.SOCIAL_INTERACTION.getValue().equals(type);
    }
    
    /**
     * 处理并存储媒体内容，返回URL
     * 注：仅处理朋友圈和头像等允许存储的媒体
     */
    private String processAndStoreMedia(ChatMessage message) {
        // 实际实现中应将Base64内容解码并存储到文件系统
        // 然后生成访问URL
        
        String userId = message.getFromUser();
        String contentType = message.getContentType();
        String timestamp = String.valueOf(System.currentTimeMillis());
        
        // 示例URL格式，实际实现应该基于实际存储路径生成
        return "/media/" + contentType + "/" + userId + "/" + timestamp + "/" + message.getMessageId();
    }
    
    /**
     * 生成唯一消息ID
     */
    private String generateMessageId() {
        return UUID.randomUUID().toString();
    }
    
    /**
     * 聊天消息模型（与ChatMessageServer中的模型兼容）
     */
    public static class ChatMessage {
        private String type;                 // 消息类型
        private String fromUser;             // 发送者
        private String toUser;               // 接收者
        private String contentType;          // 内容类型
        private String content;              // 消息内容（文本或Base64编码的媒体）
        private String messageId;            // 消息唯一ID
        private Long timestamp;              // 时间戳
        private String relatedMessageId;     // 关联消息ID（回复、引用时使用）
        private Boolean read;                // 是否已读
        private Integer chunkIndex;          // 分块索引（大文件传输）
        private Integer totalChunks;         // 总分块数（大文件传输）
        private String fileName;             // 文件名（文件传输）
        private String fileExtension;        // 文件扩展名（文件传输）
        private Long fileSize;               // 文件大小（文件传输）

        // Getters and Setters
        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getFromUser() {
            return fromUser;
        }

        public void setFromUser(String fromUser) {
            this.fromUser = fromUser;
        }

        public String getToUser() {
            return toUser;
        }

        public void setToUser(String toUser) {
            this.toUser = toUser;
        }

        public String getContentType() {
            return contentType;
        }

        public void setContentType(String contentType) {
            this.contentType = contentType;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getMessageId() {
            return messageId;
        }

        public void setMessageId(String messageId) {
            this.messageId = messageId;
        }

        public Long getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(Long timestamp) {
            this.timestamp = timestamp;
        }

        public String getRelatedMessageId() {
            return relatedMessageId;
        }

        public void setRelatedMessageId(String relatedMessageId) {
            this.relatedMessageId = relatedMessageId;
        }

        public Boolean isRead() {
            return read;
        }

        public void setRead(Boolean read) {
            this.read = read;
        }

        public Integer getChunkIndex() {
            return chunkIndex;
        }

        public void setChunkIndex(Integer chunkIndex) {
            this.chunkIndex = chunkIndex;
        }

        public Integer getTotalChunks() {
            return totalChunks;
        }

        public void setTotalChunks(Integer totalChunks) {
            this.totalChunks = totalChunks;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String getFileExtension() {
            return fileExtension;
        }

        public void setFileExtension(String fileExtension) {
            this.fileExtension = fileExtension;
        }

        public Long getFileSize() {
            return fileSize;
        }

        public void setFileSize(Long fileSize) {
            this.fileSize = fileSize;
        }
    }
    
    /**
     * 消息类型枚举
     */
    public enum MessageType {
        CHAT_MESSAGE("chat"),               // 聊天消息
        FRIEND_REQUEST("friend_request"),   // 好友请求
        FRIEND_RESPONSE("friend_response"), // 好友请求响应
        FRIEND_STATUS("friend_status"),     // 好友状态变更
        SOCIAL_POST("social_post"),         // 朋友圈发布
        SOCIAL_INTERACTION("social_interaction"), // 社交互动（点赞、评论等）
        TYPING_INDICATOR("typing"),         // 正在输入指示器
        READ_RECEIPT("read_receipt"),       // 已读回执
        MEDIA_TRANSFER("media_transfer"),   // 媒体传输
        DELIVERY_STATUS("delivery_status"), // 消息送达状态
        SYSTEM_NOTIFICATION("system"),      // 系统通知
        ERROR("error");                     // 错误消息

        private final String value;

        MessageType(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public static MessageType fromString(String text) {
            for (MessageType type : MessageType.values()) {
                if (type.value.equalsIgnoreCase(text)) {
                    return type;
                }
            }
            return null;
        }
    }
    
    /**
     * 消息内容类型枚举
     */
    public enum MessageContentType {
        TEXT("text"),           // 文本
        IMAGE("image"),         // 图片
        VIDEO("video"),         // 视频
        AUDIO("audio"),         // 语音
        FILE("file");           // 文件

        private final String value;

        MessageContentType(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public static MessageContentType fromString(String text) {
            for (MessageContentType type : MessageContentType.values()) {
                if (type.value.equalsIgnoreCase(text)) {
                    return type;
                }
            }
            return null;
        }
    }
    
    /**
     * 社交互动类型枚举
     */
    public enum SocialInteractionType {
        LIKE("like"),           // 点赞
        COMMENT("comment"),     // 评论
        SHARE("share");         // 分享

        private final String value;

        SocialInteractionType(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public static SocialInteractionType fromString(String text) {
            for (SocialInteractionType type : SocialInteractionType.values()) {
                if (type.value.equalsIgnoreCase(text)) {
                    return type;
                }
            }
            return null;
        }
    }
    
    /**
     * 消息送达状态枚举
     */
    public enum DeliveryStatus {
        SENT("sent"),           // 已发送
        DELIVERED("delivered"), // 已送达
        READ("read"),           // 已读
        PENDING("pending");     // 等待送达

        private final String value;

        DeliveryStatus(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public static DeliveryStatus fromString(String text) {
            for (DeliveryStatus status : DeliveryStatus.values()) {
                if (status.value.equalsIgnoreCase(text)) {
                    return status;
                }
            }
            return null;
        }
    }
} 